/**
 * mixin
 * 字段计算功能 & 自动填充功能
 */
import mathjs from 'mathjs/lib/browser/math'
import {
	apiapi as request
} from "@/api/request.js"

function transferToNumber(inputNumber) {
	if (isNaN(inputNumber)) {
		return inputNumber
	}
	inputNumber = '' + inputNumber
	inputNumber = parseFloat(inputNumber)
	let eformat = inputNumber.toExponential() // 转换为标准的科学计数法形式（字符串）
	let tmpArray = eformat.match(/\d(?:\.(\d*))?e([+-]\d+)/) // 分离出小数值和指数值
	let number = inputNumber.toFixed(
		Math.max(0, (tmpArray[1] || '').length - tmpArray[2])
	)
	return number
}

export default {
	watch: {
		form: {
			deep: true,
			handler: function(newval, oldval) {
				/*
				  ====== 小计、计算功能 ======
				*/
				const newNewval = JSON.parse(JSON.stringify(newval))
				// 带小计的input组件数组
				const xiaojis = this.formRuleJson.filter((rule) => {
					return rule.props.countFields != undefined
				})
				// 带小计的input组件（有可能多个）
				xiaojis.forEach((xiaoji) => {
					// 小计 计算数据的联动字段（多个）
					const countFieldsList =
						xiaoji.props.countFields == undefined ? [] :
						xiaoji.props.countFields.split(',')
					let countList =
						xiaoji.props.count == undefined ? [] : xiaoji.props.count.split(',')
					// 转换为数字（方便加）
					const countFieldDataList = countFieldsList.map((field) => {
						if (newNewval[field] == '' || newNewval[field] == undefined) {
							newNewval[field] = 0
						} else {
							newNewval[field] = Number(newNewval[field])
						}
						return newNewval[field]
					})
					// 字段 及 算法 数组处理
					if (countList.length < countFieldDataList.length - 1) {
						return uni.$u.toast("算法配置错误")
					} else if (countList.length > countFieldDataList.length - 1) {
						countList = countList.slice(0, countFieldDataList.length - 1)
					}
					// 计算公式字符串生成
					let countStringJs = ''
					countFieldDataList.forEach((num, index) => {
						// 减负数处理
						if (num < 0) {
							num = `(${num})`
						}
						if (index < countFieldDataList.length - 1) {
							countStringJs = countStringJs + num + countList[index]
						} else {
							countStringJs = countStringJs + num
						}
					})
					let res = transferToNumber(mathjs.format(mathjs.evaluate(countStringJs), 15))
					if (res == 'NaN' || res == 'Infinity') {
						res = ''
					}
					// 计算答案赋值
					newval[xiaoji.field] = res
				})
				/*
				  ====== 自动填充功能 ======
				*/
				function getUrlQuery(search) {
					const theRequest = new Object()
					const str = search.split('php?')
					const strs = str[1].split('&')
					for (let i = 0; i < strs.length; i++) {
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
					}
					return theRequest
				}
				const objKeys = Object.keys(newval)

				// 监听记录当前改变的字段 会出问题
				// let curChangeField = '' // 当前改变的字段
				// objKeys.forEach((key) => {
				// 	if (newval[key] != oldval[key]) {
				// 		curChangeField = key
				// 	}
				// })

				// 有填充功能的组件 有接口配置的 单选的 select
				const autoFillCpns = this.formRuleJson.filter((rule) => {
					return (
						rule.type == 'select' &&
						rule.effect &&
						rule.effect.fetch != '' &&
						rule.props.multiple != true &&
						rule.props.likeTableFields != '' &&
						rule.props.likeTableFields != undefined
					)
				})
				// 当前选项改变的选择器
				const curChangeCpns = autoFillCpns.filter((rule) => {
					return rule.field == this.curChangeField
				})
				// 此条件下 需要自动填充
				if (curChangeCpns.length) {
					// 当前改变的组件
					const curChangeCpn = curChangeCpns[0]
					// 当前改变的组件 的 关联表的字段数组
					const curChangeLikeTableFds =
						curChangeCpn.props.likeTableFields == undefined ? [] :
						curChangeCpn.props.likeTableFields.replace(/\s*/g, '').split(',')
					// 当前改变的组件 的 填充本表的字段数组
					const curChangetableFds =
						curChangeCpn.props.tableFields == undefined ? [] :
						curChangeCpn.props.tableFields.replace(/\s*/g, '').split(',')
					if (
						newval[curChangeCpn.field] == '' ||
						newval[curChangeCpn.field] == '0'
					) {
						curChangetableFds.forEach((field) => {
							newval[field] = ''
						})
						return
					}
					if (curChangeLikeTableFds.length != curChangetableFds.length) {
						return uni.$u.toast("算法配置错误")
					}
					// 发送请求需要的参数
					const queryObj = getUrlQuery(curChangeCpn.effect.fetch.action)
					/* 请求方式，打包后需更改为目标项目的请求方式，此方式仅为测试时使用 */
					const url = `/apim.php?_=DataAccess::data_detail&code=${queryObj.code}&${
			      queryObj.key
			    }=${newval[curChangeCpn.field]}`
					request(url, "GET").then(({
						data: {
							data
						}
					}) => {
						// 进行填充操作
						const likeTableData = data
						console.log("`````````````````````", likeTableData)
						curChangeLikeTableFds.forEach((field, index) => {
							// 填充前判断配置自动填充的字段 表中有无此字段
							if (!Object.keys(likeTableData).includes(field)) {
								return uni.$u.toast("关联表的字段,配置错误,请检查!")
							}
							if (!Object.keys(newval).includes(curChangetableFds[index])) {
								return uni.$u.toast("填充本表的字段,配置错误,请检查!")
							}
							newval[curChangetableFds[index]] = isNaN(likeTableData[field]) ?
								likeTableData[field] :
								Number(likeTableData[field])
						})
					})
				}
			}
		}
	},
}
